package com.kefu.boss.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.boss.mapper.BossVersionMapper;
import com.kefu.boss.model.BossVersion;
import com.kefu.boss.vo.BossVersionInsertVo;
import com.kefu.boss.vo.BossVersionUpdateVo;
import com.kefu.common.exception.BusinessException;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.util.Assert;
import com.kefu.common.util.JacksonUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BossVersionService extends AbstractKefuService<BossVersion> {
    @Resource
    protected BossVersionMapper bossVersionMapper;
    public BossVersion addVersion(BossVersionInsertVo bossVersionVo) {
        // 判断版本名是否已经存在
        Long count = bossVersionMapper.selectCount(Wrappers.lambdaQuery(BossVersion.class)
                .eq(BossVersion::getVersionName, bossVersionVo.getVersionName()));
        Assert.isTrue(count > 0, "版本["+ bossVersionVo.getVersionName()+"]已经存在！");
        BossVersion info = bossVersionVo.convert();
        save(info);
        logger.info("添加版本信息: {}, {}", bossVersionVo, JacksonUtil.toString(info));
        return info;
    }

    @Override
    public void deleteById(String id) {
        super.deleteById(id);
    }

    public BossVersion updateVersion(BossVersionUpdateVo bossVersionVo) {
        // 判断版本名称是否存在
        List<BossVersion> list = bossVersionMapper.selectList(Wrappers.lambdaQuery(BossVersion.class)
                .eq(BossVersion::getVersionName, bossVersionVo.getVersionName()));
        if (CollUtil.isNotEmpty(list)) {
            boolean flag = true;
            for (BossVersion ver :
                    list) {
                if (!ver.getId().equals(bossVersionVo.getId())) {
                    flag = false;
                }
            }
            if (!flag) {
                throw BusinessException.msg("版本名称["+ bossVersionVo.getVersionName()+"]已经存在！");
            }
        }
        BossVersion info = bossVersionVo.convert();
        updateById(info);
        logger.info("更新版本: {}, {}", bossVersionVo, JacksonUtil.toString(info));
        return info;
    }
}
